/*
 * maz_app_tft.c
 *
 *  Created on: 2020年9月17日
 *      Author: ChenBlue
 */

#include "maz_app.h"
#include "maz_com.h"
#include "maz_drv.h"
#include "maz_mod.h"
#include "lvgl/lvgl.h"
#include "stdio.h"
/**
 * "dlvl" variables must be defined if debug message is to be printed through the dlog/dmsg, and "dlvl" must be declared static
 */
static int dlvl = DINF;

static lv_disp_buf_t        disp_buf;
static lv_color_t           buf[LV_HOR_RES_MAX * 10];
lv_disp_drv_t               disp_drv;
unsigned int tick1 = 0;
unsigned int tick2 = 0;

osThreadId_t tft_taskHandle;
const osThreadAttr_t tft_task_attributes =
{
    .name = "tft_task",
    .priority = (osPriority_t) osPriorityNormal,
    .stack_size = 128 * 64
};

int MAZ_App_tft_preinit(void)
{
    return MAZRET_OK;
}

int MAZ_App_tft_init(void)
{
    tft_taskHandle = osThreadNew(MAZ_App_tft_task, NULL, &tft_task_attributes);
    MAZASSERT_RETVAL(NULL == tft_taskHandle, MAZRET_ENULLP, "err: osThreadNew MAZ_App_tft_task");

    return MAZRET_OK;
}

void my_disp_flush(struct _disp_drv_t *disp_drv, const lv_area_t *area, lv_color_t *color_p)
{
    unsigned int x, y;
    unsigned char picH, picL;
    unsigned char *p = (uint8_t *)color_p;

    MAZ_Mod_ili9225g_set_region(MAZMOD_ILI9225G0, area->x1, area->y1, area->x2, area->y2);

    for (y = area->y1; y <= area->y2; y++)
    {
        for (x = area->x1; x <= area->x2; x++)
        {
            RD_H;
            DC_H;

            picL = *(p++);  //数据低位在前
            picH = *(p++);
            WR_L;
            GPIO_WriteLow(GPIOB, picH);
            WR_H;

            WR_L;
            GPIO_WriteLow(GPIOB, picL);
            WR_H;
        }
    }

    lv_disp_flush_ready(disp_drv);
}

static void event_handler2(lv_obj_t *obj, lv_event_t event)
{
    if (event == LV_EVENT_VALUE_CHANGED)
    {
        printf("Button: %s\n", lv_msgbox_get_active_btn_text(obj));
    }
}

void lv_ex_msgbox_1(void)
{
    static const char *btns[] = { "Apply", "Close", "" };
    lv_obj_t *mbox1 = lv_msgbox_create(lv_scr_act(), NULL);
    lv_msgbox_set_text(mbox1, "A message box with two buttons.");
    lv_msgbox_add_btns(mbox1, btns);
    lv_obj_set_width(mbox1, 200);
    lv_obj_set_event_cb(mbox1, event_handler2);
    lv_obj_align(mbox1, NULL, LV_ALIGN_CENTER, 0, 0); /*Align to the corner*/
}

void MAZ_App_tft_task(void *argument)
{
    MAZ_Mod_ili9225g_gpio_config();
    MAZ_Mod_ili9225g_select();
    MAZ_Mod_ili9225g_init();
    MAZ_Mod_ili9225g_clear_screen(RGB565_WHITE);

#if 0  //not use lvgl
	extern const unsigned char test176x220[77448];
	MAZ_Mod_ili9225g_show_image(test176x220);
#endif
	lv_init();
	lv_disp_buf_init(&disp_buf, buf, NULL, LV_HOR_RES_MAX * 10);
	
	lv_disp_drv_init(&disp_drv);
	disp_drv.flush_cb = my_disp_flush;
	disp_drv.buffer = &disp_buf;
	lv_disp_drv_register(&disp_drv);
	tick1 = HAL_GetTick();
	lv_ex_msgbox_1();
	tick2 = HAL_GetTick();

    while(1)
    {
         lv_task_handler();
    }
}

